package cn.iocoder.yudao.module.infra.service.weather;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import cn.iocoder.yudao.framework.common.util.http.HttpUtils;
import cn.iocoder.yudao.module.infra.controller.admin.weather.vo.WeatherKeyInfoRespVO;
import cn.iocoder.yudao.module.infra.controller.admin.weather.vo.WeatherRespVO;
import cn.iocoder.yudao.module.infra.dal.dataobject.config.ConfigDO;
import cn.iocoder.yudao.module.infra.service.config.ConfigService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * 天气服务实现类
 */
@Service
@Slf4j
public class WeatherServiceImpl implements WeatherService {

    private static final String WEATHER_CONFIG_KEY = "weather.keyinfo";
    private static final String WEATHER_API_URL = "https://cn.apihz.cn/api/tianqi/tqybmoji15ip.php";

    @Resource
    private ConfigService configService;

    @Override
    public WeatherRespVO get15DaysWeather(String ip) {
        try {
            // 获取API密钥信息
            WeatherKeyInfoRespVO keyInfo = getWeatherKeyInfo();
            if (keyInfo == null || StrUtil.hasBlank(keyInfo.getId(), keyInfo.getKey())) {
                log.error("[get15DaysWeather] 获取天气API密钥信息失败");
                return null;
            }

            // 构建请求URL
            String url = buildRequestUrl(keyInfo.getId(), keyInfo.getKey(), ip);

            // 发送HTTP请求获取天气数据
            String response = HttpUtils.get(url,null);
            if (StrUtil.isBlank(response)) {
                log.error("[get15DaysWeather] 获取天气数据失败，响应为空");
                return null;
            }

            // 解析响应数据
            return JSONUtil.toBean(response, WeatherRespVO.class);
        } catch (Exception e) {
            log.error("[get15DaysWeather] 获取天气数据异常", e);
            return null;
        }
    }

    /**
     * 获取天气API密钥信息
     *
     * @return 密钥信息
     */
    private WeatherKeyInfoRespVO getWeatherKeyInfo() {
        ConfigDO config = configService.getConfigByKey(WEATHER_CONFIG_KEY);
        if (config == null || StrUtil.isBlank(config.getValue())) {
            return null;
        }

        try {
            return JSONUtil.toBean(config.getValue(), WeatherKeyInfoRespVO.class);
        } catch (Exception e) {
            log.error("[getWeatherKeyInfo] 解析天气API密钥信息异常", e);
            return null;
        }
    }

    /**
     * 构建请求URL
     *
     * @param id  API ID
     * @param key API 密钥
     * @param ip  IP地址
     * @return 请求URL
     */
    private String buildRequestUrl(String id, String key, String ip) {
        // 如果ip为本机127.0.0.1，则默认转化为115.171.234.79
        if (ip.equals("127.0.0.1")) {
            ip = "115.171.234.79";
        }
        return String.format("%s?id=%s&key=%s&ip=%s", WEATHER_API_URL, id, key, ip);
    }
}

